
import mongoose from 'mongoose'

const Course = mongoose.model('Course')
const Comment = mongoose.model('Comment')
const User = mongoose.model('User')

export async function saveComment ({email, courseid, tid, content, commentid}) {
  let author = await User.findOne({email: email})
  let course = await Course.findOne({courseid: courseid})
  let comment = {}
  console.log('hhhhhh')
  console.log(tid)
  
  if (commentid) {
    comment = await Comment.findById(commentid)
    console.log(11111)
    console.log(comment)
    let reply = {
      from: author._id,
      to: tid,
      content: content,
    }
    comment.reply.push(reply)
  } else {
    comment = new Comment({
      authorinfo: author._id,
      courseid,
      content
    })

    console.log(22222)
    console.log(comment)
  }

  console.log('aaaaaaa')
  console.log(commentid)
  
  let data = await comment.save()
  
  return {
    data
  }
}

export async function getComments ({courseid, page}) {
  page = page || 1
  
  let data = await Comment.find({ courseid: courseid })
    .sort({ 'createdAt': -1 }).limit(10).skip(10*(page-1))
    .populate('authorinfo', '_id email')
    .populate('reply.from reply.to', 'email')
    .exec()
   console.log(999999) 
   console.log(JSON.stringify(data))

  let result = [] 
  data.forEach((item) => {
    let obj = {}
    obj['commentid'] = item['_id']
    obj['author'] = item['authorinfo']['email']
    obj['tid'] = item['authorinfo']['_id']
    obj['content'] = item['content']
    obj['createdAt'] = item['createdAt']
    obj['reply'] = item['reply']
    result.push(obj)
  })

  let count = await Comment.find({ courseid: courseid }).count()
  return {
    data: result,
    count
  }
}
